//
//  SecondViewController.m
//  chollos2
//
//  Created by Juan Soler Company on 11/04/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "SecondViewController.h"
#import "oferta.h"
#import "JSON.h"
#import "CustomCell.h"

@interface SecondViewController ()

@end

@implementation SecondViewController

@synthesize listData;
@synthesize offerList;
@synthesize receivedData;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.title = NSLocalizedString(@"Cerca de ti", @"Cerca de ti");
        self.tabBarItem.image = [UIImage imageNamed:@"73-radar"];
        
    }
    return self;
}
							
- (void)viewDidLoad
{
    self.listData = nil;
    [super viewDidLoad];
    [self get:@"http://qa.apps3.com/API/api.php?q=obtenirProperes&lat=41.384443&lng=2.155443&rad=200"];
}

- (void)viewDidUnload
{
    [self setOfferList:nil];
    offerList = nil;
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
    } else {
        return YES;
    }
    
}


/*
    VISUAL FUNCTIONS
 
 */

#pragma mark - 
#pragma mark Table View Data Source Methods


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	return [self.listData count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView2 cellForRowAtIndexPath:(NSIndexPath *)indexPath {

        static NSString *SimpleTableIdentifier = @"MyIdentifier";
        CustomCell *cell = (CustomCell *)[tableView2 dequeueReusableCellWithIdentifier: SimpleTableIdentifier];
        if (cell == nil) { 
            
            [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
            cell = tblCell;
        }
        oferta * of = [[oferta alloc]init];
    
        NSUInteger row = [indexPath row];
    	of = [listData objectAtIndex:row]; 
        NSString *sDistance = [NSString stringWithFormat: @"%.0f",of.distancia];
    
        [cell setTitle:of.nom];
        [cell setDist:sDistance];
    
        if(of.source == @"Restalo"){
            [cell setImage:@"Restalo"];
        }
        else if(of.source == @"ResBar"){
            [cell setImage:@"ResBar"];
        }
        else if(of.source == @"Groupon"){
            [cell setImage:@"Groupon"];
        }
        else if(of.source == @"Groupalia"){
            [cell setImage:@"Groupalia"];
        }
    
        
        return cell;
    
}


-(void)renderData:(NSMutableArray *)data{
    
    self.listData = data;
    [self.offerList reloadData];
    
    NSString* badge = [NSString stringWithFormat:@"%d", [data count]];
    
    [[[[[self tabBarController] tabBar] items] objectAtIndex:1] setBadgeValue:badge];
    
    
}

- (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath { 
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    UIAlertView *alert = [[UIAlertView alloc] init];
    [alert setTitle:@"Tapped"];
    [alert setMessage:cell.textLabel.text];
    [alert addButtonWithTitle:@"Ok"];
    [alert setDelegate:self];
    [alert show]; 
}



/*
        CONNECTION TO SERVER FUNCTIONS!!
 
 */



- (void)get: (NSString *)urlString {
 	
 	NSLog ( @"GET: %@", urlString );
    
 	self.receivedData = [[NSMutableData alloc] init];
 	
    NSURLRequest *request = [[NSURLRequest alloc]
 							 initWithURL: [NSURL URLWithString:urlString]
 							 cachePolicy: NSURLRequestReloadIgnoringLocalCacheData
 							 timeoutInterval: 10
 							 ];
    
    NSURLConnection *connection = [[NSURLConnection alloc]
 								   initWithRequest:request
 								   delegate:self
 								   startImmediately:YES];
 	if(!connection) {
 		NSLog(@"connection failed :(");
 	} else {
 		NSLog(@"connection succeeded  :)");
 		
 	}
    
}


- (void)post: (NSString *)urlString {
 
}	

// ====================
// Callbacks
// ====================

#pragma mark NSURLConnection delegate methods
- (NSURLRequest *)connection:(NSURLConnection *)connection
 			 willSendRequest:(NSURLRequest *)request
 			redirectResponse:(NSURLResponse *)redirectResponse {
 	NSLog(@"Connection received data, retain count");
    return request;
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
 	NSLog(@"Received response: %@", response);
 	
    [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
 	NSLog(@"Received %d bytes of data", [data length]); 
 	
    [receivedData appendData:data];
 	NSLog(@"Received data is now %d bytes", [receivedData length]); 
    
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
 	NSLog(@"Error receiving response: %@", error);
}

/* Callback executed when data is obtained */

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // Once this method is invoked, "responseData" contains the complete result
 	NSLog(@"Succeeded! Received %d bytes of data", [receivedData length]); 
 	
 	NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
 	NSLog(@"Succeeded! Received %@ bytes of data", dataStr); 
   
    [self ofertesProperes:dataStr];
   
    
}
    
/*  
    Parsejador del retorn
 
    agafa json i retorna un NSMutableArray on a cada posicio
    hi ha un objecte Oferta
    
 */

-(void)ofertesProperes:(NSString *)data{
    
    
    NSDictionary *results = [data JSONValue];  
    NSMutableArray *retorn = [[NSMutableArray alloc]init];   
    
    /*Parse and add Restalo elements to array*/
    NSDictionary *elemsRestalo = [results objectForKey:@"Restalo"];
    
    for(NSDictionary *fields in elemsRestalo){
        
        oferta *offer = [[oferta alloc]init];
        [offer setNom:[fields valueForKey:@"name"]];
        [offer setLat:[[fields valueForKey:@"lat"] floatValue]];
        [offer setLng:[[fields valueForKey:@"lng"] floatValue]];
        [offer setIdOferta:[[fields valueForKey:@"id"]intValue]];
        [offer setIdRestalo:[[fields valueForKey:@"idrestalo"]intValue]];
        [offer setDescripcion:[fields valueForKey:@"description"]];
        [offer setDistancia:[[fields valueForKey:@"distance"]floatValue]];
        [offer setLink:[fields valueForKey:@"link"]];
        [offer setSource:@"Restalo"];
        [retorn addObject:offer];
    }
    
    /*Parse Restaurantes de Barcelona elements and add them to the return array*/
    NSDictionary *elemsResBar = [results objectForKey:@"ResBar"];
    
    for(NSDictionary *fields in elemsResBar){
        
        oferta *offer = [[oferta alloc]init];
        [offer setNom:[fields valueForKey:@"nombre"]];
        [offer setLat:[[fields valueForKey:@"lat"] floatValue]];
        [offer setLng:[[fields valueForKey:@"lng"] floatValue]];
        [offer setIdOferta:[[fields valueForKey:@"id"]intValue]];
        [offer setDescripcion:[fields valueForKey:@"oferta"]];
        [offer setDistancia:[[fields valueForKey:@"distance"]floatValue]];
        [offer setLink:[fields valueForKey:@"link"]];
        [offer setSource:@"ResBar"];
        [retorn addObject:offer];
    }
    
    /*Groupon and Groupalia*/
    
    NSDictionary *elemsCupon = [results objectForKey:@"Cupon"];
    
    for(NSDictionary *fields in elemsCupon){
        
        oferta *offer = [[oferta alloc]init];
        [offer setNom:[fields valueForKey:@"title"]];
        [offer setLat:[[fields valueForKey:@"lat"] floatValue]];
        [offer setLng:[[fields valueForKey:@"lng"] floatValue]];
        [offer setIdOferta:[[fields valueForKey:@"id"]intValue]];
        [offer setDescripcion:[fields valueForKey:@"description"]];
        [offer setDistancia:[[fields valueForKey:@"distance"]floatValue]];
        [offer setLink:[fields valueForKey:@"gurl"]];
        [offer setSource:[fields valueForKey:@"type"]];
        [retorn addObject:offer];
    }
    
   
    [self renderData:retorn];
        
}




@end
